package com.msb.juc.c_024;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CountDownLatch;

/**
 * 关于跳表：https://blog.csdn.net/sunxianghuang/article/details/52221913
 */
public class T01_ConcurrentMap {

    public static void main(String[] args) {
        Map<String, String> map = new ConcurrentHashMap<>();
        /*
        TreeMap，底层红黑树，没有ConcurrentTreeMap，
        因为 CAS操作用在树节点上非常复杂。
        因此使用跳表来进行高并发排序
        高并发并且排序，跳表实现，方便查询

        在已有链表上取一些关键元素，再构成一串链表；如此反复
        查找时从顶层开始查找，目标是减小查找的范围，来降低时间复杂度
        */
        Map<String, String> map1 = new ConcurrentSkipListMap<>();
        Map<String, String> map2 = new Hashtable<>();
        Map<String, String> map3 = Collections.synchronizedMap(new HashMap<>());
        Random r = new Random();
        Thread[] threads = new Thread[100];
        CountDownLatch latch = new CountDownLatch(threads.length);
        long start = System.currentTimeMillis();
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    map.put("a" + r.nextInt(100000), "a" + r.nextInt(100000));
                    latch.countDown();
                }
            });
        }

        Arrays.asList(threads).forEach(thread -> thread.start());

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();
        System.out.println(end - start);
        System.out.println(map.size());
    }

}
